package com.dgty.dg_common.network;
import com.blankj.utilcode.util.ActivityUtils
import com.dgty.dg_common.ui.ActivityHelper
import com.dgty.dg_common.util.UserUtil
import okhttp3.Interceptor
import okhttp3.Response
import org.json.JSONObject
import java.nio.charset.StandardCharsets

/**
 * Title: TokenInterceptor.kt
 * Description:处理token过期的情况
 * Created DateTime: 2023-03-14
 * Created by xxl.
 */
class TokenInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        val responseBody = response.body
        responseBody?.let {
            val source = responseBody.source()
            source.request(Long.MAX_VALUE)
            val buffer = source.buffer
            try {
                val result = buffer.clone().readString(StandardCharsets.UTF_8)
                val jsonObject = JSONObject(result)
                val code = jsonObject.getInt("code")
                //Token过期错误码
//                {"code":401,"msg":"Token无效","success":false}
                if (code == 401){
                    //清除用户相关数据
                    UserUtil.sInstance.cleanUserInfo()
                    //跳转登录页面
                    ActivityHelper.startLoginMain()
                    ActivityUtils.finishAllActivities()
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
        return response
    }
}
